<?php
require 'functions.php';

if ($_SERVER['REQUEST_METHOD']!== 'POST') {
  header('HTTP/1.1 405 Method Not Allowed');
  return;
}

// 获取请求中的用户输入数据
$username = input('username');
$password = input('password');
$pwd_again = input('pwd_again');
$code =input('code');

// 获取请求中的用户输入数据
$hasError = false;
$inputBag = ['username' => ''];
$errorBag = [
  'username' => '',
  'password' => '',
  'pwd_again' => '',
  'code'=>''
];

// 数据验证
if (trim($username) == '') {
	$hasError = true;
	$errorBag['username'] = '用户名不能为空';
}else if (strlen($password) < 6) {
	$hasError = true;
	$errorBag['password'] = '密码长度必须大于6位';
}else if ($pwd_again !== $password) {
	$hasError = true;
	$errorBag['pwd_again'] = '两次输入的密码必须一致';
}else if (trim($code) == '') {
	$hasError = true;
	$errorBag['code'] = '验证码不得为空';
}else if ($code != $_SESSION['code']) {
	$hasError = true;
	$errorBag['code'] = '验证码错误';
	unset($_SESSION['code']);
}
// 验证用户名是否已经被注册
$sql = 'select id from users where user_name=?';
$args = [$username];
$data = query($sql,$args);
if (count($data)>0) {
	$hasError = true;
	$errorBag['username'] = '该用户已存在';
}
// 如果数据验证出现错误，则把错误包数据存入session，重定向到表单页面
$inputBag['username'] = $username;
$_SESSION['has_error'] = $hasError;
$_SESSION['input_bag'] = $inputBag;
$_SESSION['error_bag'] = $errorBag;
if ($hasError) {
	header('Location:'. url('register'));
	return;
}


// 验证通过，写入数据库
$password = password_hash($password,PASSWORD_BCRYPT);
$sql = 'insert into users(user_name,password,register_time) values(?,?,now())';
$args = [$username,$password];
if (execute($sql,$args)) {
	header('Location:'. url('signin'));
}else{
	header('Location:'. url('register'));
}